const express=require('express');
const app=express();
const bodyParser=require('body-parser');
const models=require('../db/models')

app.use(express.json());
app.use(express.urlencoded());
app.use(bodyParser.urlencoded({extended:true}));


app.get('/list/:status/:page',async (req,res,next)=>{
 try{

  let {status,page}=req.params;
  let where={};
  let limit=10;
  let offset=(page-1)*limit;
  if(status!=-1){
    where.status=status;
  }

  let list=await models.Todo.findAndCountAll({
   where,
   offset,
   limit
  });

  
  res.json({
    list,
    message:'列表查询成功'
  })

 }catch(err){
   next(err)
 }
})

app.post('/create',async (req,res,next)=>{
  try{

  let{name,deadline,content}=req.body;

  let todo=await models.Todo.create({
    name,
    deadline,
    content
  });
  res.json({
    todo,
    message:'任务创建成功'
  })

  }catch(err){
     next(err)
  }
})

app.post('/update',async (req,res,next)=>{

  try{

    let{id,name,deadline,content}=req.body;
    let todo=await models.Todo.findOne({
    where:{
      id
    }
  })

  if(todo){
    todo=await todo.update({
      name,
      deadline,
      content
    })
  }

  
  res.json({
    todo
  })

  }catch(err){
    next(err)
  }
})

app.post('/update_status',async(req,res,next)=>{
 try{

  let{ id,status}=req.body;
  let todo=await models.Todo.findOne({
    where:{id}
  });

  if(todo && todo.status !=status){
     todo=await todo.update({
        status
      })
  }
  res.json({
    todo
  })

 }catch(err){
   next(err)
 }
})


app.use((err,req,res,next)=>{
   if(err){
     res.status(500).json({
       message:err.message
     })
   }
})

app.listen(3000,()=>{
   console.log('the server is running')
})